import SwiftUI

struct ContentView: View {
    @State private var selectedImage: UIImage?
    @State private var isShowingImagePicker = false
    @State private var currentFilter: ImageFilterManager.FilterType = .none
    
    var body: some View {
        VStack {
            // Image display area
            if let image = selectedImage {
                Image(uiImage: image)
                    .resizable()
                    .scaledToFit()
                    .frame(maxHeight: 500)
                    .cornerRadius(10)
                    .padding()
                
                // Filter selection
                ScrollView(.horizontal, showsIndicators: false) {
                    HStack {
                        FilterButton(title: "Sepia", filter: .sepia)
                        FilterButton(title: "Noir", filter: .noir)
                        FilterButton(title: "Mono", filter: .mono)
                        FilterButton(title: "Chrome", filter: .chrome)
                    }
                    .padding()
                }
                
                // Save and Reset buttons
                HStack {
                    Button("Save") {
                        saveImage()
                    }
                    .disabled(selectedImage == nil)
                    
                    Button("Reset") {
                        resetImage()
                    }
                    .disabled(selectedImage == nil)
                }
                .padding()
            }
            
            // Image Picker Button
            Button("Select Photo") {
                isShowingImagePicker = true
            }
            .padding()
            .sheet(isPresented: $isShowingImagePicker) {
                ImagePicker(selectedImage: $selectedImage)
            }
        }
        .background(AppTheme.backgroundColor)
    }
    
    private func FilterButton(title: String, filter: ImageFilterManager.FilterType) -> some View {
        Button(title) {
            applyFilter(filter)
        }
        .padding()
        .background(currentFilter == filter ? AppTheme.primaryColor : Color.gray.opacity(0.2))
        .foregroundColor(currentFilter == filter ? .white : .primary)
        .cornerRadius(10)
    }
    
    private func applyFilter(_ filter: ImageFilterManager.FilterType) {
        guard let originalImage = selectedImage else { return }
        
        if let filteredImage = ImageFilterManager.shared.applyFilter(to: originalImage, filterType: filter) {
            selectedImage = filteredImage
            currentFilter = filter
        }
    }
    
    private func saveImage() {
        guard let image = selectedImage else { return }
        
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
    }
    
    private func resetImage() {
        selectedImage = nil
        currentFilter = .none
    }
}